package com.ruoyi.base.redis.role;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.platform.system.menu.manager.MenuManager;
import com.ruoyi.platform.system.menu.pojo.MenuTreeDTO;
import com.ruoyi.platform.system.role.manager.RoleManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 角色菜单redis
 *
 * @author lcf
 */
@Component
public class RoleMenuRedis {

    @Autowired
    public StringRedisTemplate redisTemplate;
    @Autowired
    private RoleManager roleManager;

    /**
     * 网格key
     */
    private final String key = "role_menu";

    /**
     * 缓存时间(h)
     */
    private long cache_time = 1;
    /**
     * 过期时间单位
     */
    private TimeUnit timeUnit = TimeUnit.HOURS;

    /**
     * 删除缓存
     */
    public void delCache(Long roleId) {
        redisTemplate.delete(getKey(roleId));
    }

    /**
     * 缓存角色菜单列表
     */
    public void cache(Long roleId, List<MenuTreeDTO> list) {
        redisTemplate.boundValueOps(getKey(roleId)).set(JSON.toJSONString(list), cache_time, timeUnit);
    }

    /**
     * 获取角色菜单列表
     */
    public List<MenuTreeDTO> getList(Long roleId) {
        String json = redisTemplate.boundValueOps(getKey(roleId)).get();
        if (json != null) {
            return JSON.parseArray(json, MenuTreeDTO.class);
        }

        List<MenuTreeDTO> list = roleManager.getRoleMenuTree(Collections.singletonList(roleId));
        cache(roleId, list);
        return list;
    }

    /**
     * 获取菜单列表
     */
    public List<MenuTreeDTO> getList() {
        String json = redisTemplate.boundValueOps(getKey(null)).get();
        if (json != null) {
            return JSON.parseArray(json, MenuTreeDTO.class);
        }

        List<MenuTreeDTO> list = MenuManager.getMenuList();
        cache(null, list);
        return list;
    }

    /**
     * 获取key
     */
    private String getKey(Long roleId) {
        return roleId == null ? key : key + roleId;
    }
}
